package com.MedDroid.control;

import com.MedDroid.MainApp;
import com.MedDroid.control.message.Message;
import com.MedDroid.entities.Permissions;
import com.MedDroid.entities.User;

/**
 * Created with IntelliJ IDEA.
 * User: Romen
 * Date: 19/11/13
 * Time: 9:39 PM
 * Description:
 */
public class AuthenticationControl extends AbstractControl
{
	int CurrentUser;
	Permissions Access;

	public AuthenticationControl(MainApp A)
	{
		super(A);
		CurrentUser = -1;
		Access = new Permissions(Permissions.UZero);
	}

	@Override
	public Message processMessage(Message Msg)
	{
		//On error
		return new Message(this,0,"NULL");
	}

	//INCOMPLETE
	public boolean attemptLogin(String LoginName, String Password)
	{
		User LoginUser = findUser(LoginName);
		if (LoginUser != null)
		{
			if (checkPassword(Password,LoginUser))
			{
				CurrentUser = LoginUser.getUserID();
				return true;
			}
			else
			{
				MainApp.log("Incorrect Password");
				return false;
			}
		}
		MainApp.log("Incorrect User Name");
		return false;
	}

	public boolean attemptLogout()
	{
		CurrentUser = -1;
		return true;
	}

	public User getLoginUser()
	{
		if (CurrentUser != -1)
		{
			return App.getDatabase().findUser(User.UserIDStr,Integer.toString(CurrentUser));
		}
		return null;
	}

	public Permissions getAccess()
	{
		return getLoginUser().getAccess();
	}

	private User findUser(String LoginName)
	{
		return App.getDatabase().findUser(User.LoginNameStr,LoginName);
	}

	private boolean checkPassword(String Password, User LoginUser)
	{
		return LoginUser.getPassword().equals(Password);
	}
}
